﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Web.UI.HtmlControls;
using Metodesa.Logic;
using METODESA.Server.Data.Exceptions;
using METODESA.Server.Data.METODESA.Entity;
using METODESA.Server.Data.METODESA.Nhibernate;
using Metodesa.Tools;

namespace Metodesa.Views.Home
{
    public partial class ListVentas : System.Web.UI.Page
    {
        private string clienteId;
        private string empleadoId;
        private string tPago;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["User"] != null)  //sesion de usuario
            {
                Empleado usuario = (Empleado)Session["User"];
            }
            else
            {
                Response.Redirect("../../Views/Home/Index.aspx", true); //se redirecciona
            }

            PanelAdd.Visible = false;
            PanelEdit.Visible = false;
            Calendario.Visible = false; //Nuevo
            Calendario2.Visible = false;
            label.Visible = false;

            String action = Request.QueryString.Get("a");

            if (action != null)
            {
                if (action.Equals("add"))
                {
                    PanelAdd.Visible = true;
                }
                if (action.Equals("s"))
                {
                    PanelEdit.Visible = true;
                    if (ClienteList2.SelectedValue != null)
                    {
                        clienteId = ClienteList2.SelectedValue;
                        empleadoId = EmpleadoList2.SelectedValue;
                        tPago = PagoList2.SelectedValue;

                    }
                    prepareEdit();
                }
            }

            String cale = Request.QueryString.Get("b");
            if (cale != null)
            {
                if (cale.Equals("muestra"))
                {
                    Calendario.Visible = true; // Calendario de agregar
                }
                else if (cale.Equals("muestra2"))
                {
                    Calendario2.Visible = true; // Calendario de editar
                }
            }

        }

        private void prepareEdit()
        {
            try
            {
                int ids = int.Parse(Request.QueryString["id"]);
                EditId.Value = ids.ToString();
                OrdenVenta venta = VentasDao.getVentaById(ids);
                bool closed = venta.Estado == 1;
                if (!closed)
                {
                    PanelEdit.Visible = true;
                    teFecha.Text = venta.Fecha;

                    IList<Empleado> listEmpleados;
                    IList<Cliente> listClientees;

                    if (Session["ListEmpleados"] == null || ((IList<Empleado>)Session["ListEmpleados"]).Count == 0)
                    {
                        listEmpleados = EmpleadoDao.getAllEmpleado();
                        Session.Add("ListEmpleados", listEmpleados);
                    }
                    else
                    {
                        listEmpleados = (IList<Empleado>)Session["ListEmpleados"];
                    }

                    if (Session["ListClientees"] == null)
                    {
                        listClientees = ClienteDao.getAllClient();
                        Session.Add("ListClientees", listClientees);
                    }
                    else
                    {
                        listClientees = (IList<Cliente>)Session["ListClientees"];
                    }

                    ClienteList2 = VentasTools.ListClientes(listClientees, ClienteList2);
                   
                    ClienteList2.SelectedValue = venta.Cliente.Id.ToString();
                    PagoList2.SelectedValue = venta.TipoPago;
                    EmpleadoList2 = ComprasTools.ListEmpleados(listEmpleados, EmpleadoList2);
                    EmpleadoList2.SelectedValue = venta.Empleado.Id.ToString();

                }
            }
            #region manejo de errores
            catch (Exception exception)
            {
                Session.Add("Error", exception);
                Response.Redirect("../../Views/Home/Error.aspx", true);
            }
            #endregion
        }

        protected void FindButton_Click(object sender, EventArgs e)
        {
            IList<OrdenVenta> lista;
            if (option != null && option.SelectedItem != null)
                lista = VentaLogic.processSearch(searchbox.Text, type.SelectedValue, option.SelectedValue);
            else
                lista = VentaLogic.processSearch(searchbox.Text, type.SelectedValue, "");

            HtmlTable table = VentasTools.ListVenta(lista);

            if (table != null)                   //si la tabla esta vacia
            {
                ListVenta.Controls.Add(table);
                ListVenta.Visible = true;           //muestra la lista
            }
            else
            {
                label.Visible = true;
                label.ForeColor = Color.DarkRed;
                label.Text = "No se encontraron ventas que cumplan con la búsqueda";
            }
        }

        protected void Calendar1_SelectionChanged(object sender, EventArgs e)
        {
            taFecha.Text = Calendar1.SelectedDate.ToShortDateString();
            Calendario.Visible = false;
        }

        protected void AddButton_Click(object sender, EventArgs e)
        {
            addVenta();
        }

        private void addVenta()
        {
            try
            {
                VentaLogic.add(taFecha.Text, EmpleadoList.SelectedValue, ClienteList.SelectedValue,PagoList.SelectedValue);
                label.Visible = true;
                label.ForeColor = Color.Blue;
                label.Text = "Venta agregada satifactoriamente";
                PanelAdd.Visible = false;
            }
            #region manejo de errores
            catch (EntityCouldntBeSaved exception)
            {
                label.Visible = true;
                label.ForeColor = Color.Red;
                label.Text = "No se pudo agregar la venta";
                PanelAdd.Visible = true;
                Session.Add("Error", exception);
            }

            catch (Exception exception)
            {
                Session.Add("Error", exception);
                Response.Redirect("../../Views/Home/Error.aspx", true);
            }
            #endregion
        }

        protected void EditButton_Click(object sender, EventArgs e)
        {
            EditVenta();
        }


        private void EditVenta()
        {
            try
            {
                VentaLogic.edit(int.Parse(EditId.Value), teFecha.Text, empleadoId, clienteId,tPago);
                label.Visible = true;
                label.ForeColor = Color.Blue;
                label.Text = "Venta modificada satifactoriamente";
                PanelEdit.Visible = false;
                Calendario2.Visible = false;

            }
            #region manejo de errores
            catch (EntityCouldntBeUpdated exception)
            {
                label.Visible = true;
                label.ForeColor = Color.Red;
                label.Text = "No se pudo modificar la venta";
                PanelAdd.Visible = true;
                Session.Add("Error", exception);
            }

            catch (Exception exception)
            {
                Session.Add("Error", exception);
                Response.Redirect("../../Views/Home/Error.aspx", true);
            }
            #endregion
        }

        protected void Calendar2_SelectionChanged(object sender, EventArgs e)
        {
            teFecha.Text = Calendar2.SelectedDate.ToShortDateString();
            Calendario2.Visible = false;

        }


        /// <summary>
        /// Prepara el agregado
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void PrepareAddButton_Click(object sender, EventArgs e)
        {
            PanelAdd.Visible = true;
            IList<Empleado> listEmpleados;
            IList<Cliente> listClientees;

            if (Session["ListEmpleados"] == null)    //si listempleados es null
            {
                listEmpleados = EmpleadoDao.getAllEmpleado();
                Session.Add("ListEmpleados", listEmpleados);
            }
            else
            {
                listEmpleados = (IList<Empleado>)Session["ListEmpleados"];
            }
            if (Session["ListClientees"] == null)
            {
                listClientees = ClienteDao.getAllClient();
                Session.Add("ListClientees", listClientees);
            }
            else
            {
                listClientees = (IList<Cliente>)Session["ListClientees"];
            }
            ClienteList = VentasTools.ListClientes(listClientees, ClienteList);
            EmpleadoList = ComprasTools.ListEmpleados(listEmpleados, EmpleadoList);
        }
    }
}
